package com.mspbots.rule.exceptions.cw;

import com.mspbots.cw.request.TenantTimeEntryDTO;
import com.mspbots.cw.request.TenantUsersMappingDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * com.mspbots.rule.exceptions.timeentry.IncludingPassword
 *
 * @author Jun Zhou
 * @date 14:16 2019/7/1
 **/
@Slf4j
@Rule(name = "IncludingPassword", description = "Time log has word “password” and followed with a possible password")
public class IncludingPassword extends CwBaseRule implements IcwBaseRule {


    @Condition
    @Override
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {
        Flux<Boolean> flux = this.coreClient.getFlux("/user-mapping/user",
                Map.of("tenantId", tenantRuleDTO.getTenantId(), "tenantUserId", entry.getTenantUserId()))
                .flatMap(mapping -> {
                    this.tenantUserMappingDTO = this.objectMapper.convertValue(mapping, TenantUsersMappingDTO.class);
                    return hasMessage(entry);
                })
                .flatMap(res -> Flux.just(this.objectMapper.convertValue(res, Integer.class) > 0))
                .flatMap(hasMsg -> {
                            if (hasMsg) {
                                return Flux.just(false);
                            }
                            boolean result = entry.getDescription().toLowerCase().contains("password is")
                                    || entry.getDescription().toLowerCase().contains("password:")
                                    || entry.getDescription().toLowerCase().contains("password :")
                                    || entry.getDescription().toLowerCase().contains("password -");

                            return Flux.just(result);
                        }
                );
        return flux.blockFirst();

        /*try {
            if (!setUserMapping(entry.getTenantUserId()) || super.checkMessage(entry)) {
                return false;
            }

            return entry.getDescription().toLowerCase().contains("password");
        } catch (Exception e) {
            log.error("IncludingPassword rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
            e.printStackTrace();
        }
        return false;*/
    }


//    @Override
//    protected Mono<TenantUsersMappingDTO> setUserMapping(Long tenantUserId) {
//        return this.coreClient.get("/user-mapping/user",
//                Map.of("tenantId", tenantRuleDTO.getTenantId(), "tenantUserId", tenantUserId));
//    }

}
